#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/26 19:00
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : token.py
# @Software: PyCharm
# @Desc    :
import datetime

import jwt
from django.conf import settings


def create_token(payload: dict, timeout_hours: int = 7 * 24) -> str:
    """
    生成JWT令牌

    :param payload: 自定义载荷（如{'user_id': 1, 'username': 'summer'}）
    :param timeout_hours: 过期时间（单位：小时，默认7天）
    :return: 生成的JWT令牌字符串
    """
    # 1. 密钥
    secret_key = settings.JWT_TOKEN

    # 2. 构建标准载荷（使用带时区的UTC时间）
    expire_time = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=timeout_hours)
    standard_payload = {
        **payload,
        'exp': expire_time,
        'iat': datetime.datetime.now(datetime.timezone.utc)
    }

    # 3. 定义JWT头部
    headers = {
        'typ': 'JWT',
        'alg': 'HS256'
    }

    # 4. 生成并返回令牌
    try:
        generated_token = jwt.encode(
            payload=standard_payload,
            key=secret_key,
            algorithm='HS256',
            headers=headers
        )
        return generated_token if isinstance(generated_token, str) else generated_token.decode('utf-8')
    except Exception as e:
        raise ValueError(f"JWT令牌生成失败: {str(e)}")


if __name__ == '__main__':
    import os
    import django

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "notify.settings")  # 替换为你的项目settings路径
    django.setup()

    # 测试用例1：生成并验证令牌
    test_payload = {
        "user_id": 1001,
        "username": "test_user",
        "role": "admin"
    }
    test_timeout = 1  # 1小时后过期

    # 生成令牌
    token = create_token(payload=test_payload, timeout_hours=test_timeout)
    print(f'生成的JWT令牌: {token} \n')

    # 验证令牌（模拟服务端解码流程）
    try:
        decoded = jwt.decode(
            jwt=token,
            key=settings.JWT_TOKEN,
            algorithms=["HS256"],
            options={"verify_exp": True}
        )
        print(f'解码后的载荷: {decoded} \n')

        # 检查自定义字段
        assert decoded["user_id"] == test_payload["user_id"], "user_id不匹配"
        assert decoded["username"] == test_payload["username"], "username不匹配"
        print("自定义字段验证通过")

        # 检查过期时间（统一使用带时区的UTC时间）
        exp_time = datetime.datetime.fromtimestamp(decoded["exp"], tz=datetime.timezone.utc)
        expected_exp = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=test_timeout)
        time_diff = abs((exp_time - expected_exp).total_seconds())
        assert time_diff < 60, f"过期时间误差过大（{time_diff}秒）"
        print(f"过期时间验证通过（预期{test_timeout}小时后过期）")

    except jwt.ExpiredSignatureError:
        print("令牌已过期")
    except jwt.InvalidTokenError as e:
        print(f"令牌无效：{e}")
    except AssertionError as e:
        print(f"数据验证失败：{e}")
